import Vue from 'vue'
import VueRouter from 'vue-router'

import Register from '@/views/Register'
import Login from '@/views/Login'
import Layout from '@/views/Layout'
import Home from '@/views/Layout/Home'
import UserInfo from '@/views/Layout/UserInfo'
import UserAvatar from '@/views/Layout/UserAvatar'
import UserPwd from '@/views/Layout/UserPwd'
import ArticleCate from '@/views/Layout/Article/ArticleCate'
import ArtList from '@/views/Layout/Article/ArtList'

import store from '@/store'

Vue.use(VueRouter)

// 把下面的代码粘贴到路由模块中对应的位置，即可防止路由报错的问题
const originalPush = VueRouter.prototype.push
VueRouter.prototype.push = function push (location) {
  return originalPush.call(this, location).catch(err => err)
}

// 把下面的代码粘贴到路由模块中对应的位置，即可防止路由报错的问题
const originalReplace = VueRouter.prototype.replace
VueRouter.prototype.replace = function replace (location) {
  return originalReplace.call(this, location).catch(err => err)
}

const routes = [
  {
    path: '/',
    component: Layout,
    redirect: '/home',
    children: [
      {
        path: 'home',
        component: Home
      }, {
        path: 'user-info',
        component: UserInfo
      }, {
        path: 'user-avatar',
        component: UserAvatar
      }, {
        path: 'user-pwd',
        component: UserPwd
      }, {
        path: 'art-cate',
        component: ArticleCate
      }, {
        path: 'art-list',
        component: ArtList
      }
    ]
  },
  {
    path: '/register',
    component: Register
  }, {
    path: '/login',
    component: Login
  }
]

const router = new VueRouter({
  mode: 'hash',
  // base: process.env.BASE_URL,// 路由的基地址
  routes
})
// 白名单数组，写在这里的路径是不需要token就可访问
const whiteList = ['/login', '/register', '/404']
router.beforeEach((to, from, next) => {
  const { token } = store.state.user
  // 有token直接放行
  if (token) {
    next()
  } else {
    // 否则，没有token
    if (whiteList.includes(to.path)) { // 你要去的路径在白名单中，直接放行
      next()
    } else {
      // 回到登录页
      next('/login')
    }
  }
})

export default router
